package AnnotationCache.core;

import AnnotationCache.Run.Model;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;

/**
 * Created by wangyg 
 * on 2017/7/31 17:25
 */
@Component
@Aspect
@EnableAspectJAutoProxy
public class RedisAop {

	private final DefaultHandler handler=new DefaultHandler("10.128.90.194",6379);

	@Pointcut("@annotation(AnnotationCache.annotation.RedisCached)")
	public void pointCut() {

	}
	@Around("pointCut()")
	public Object around(ProceedingJoinPoint pjp){
		Object o=null;
		try {
			//获取类名
			String clazzName = pjp.getTarget().getClass().getName();
			//获取方法名
			String methodName = pjp.getSignature().getName();
			//获取参数
			Object[] args = pjp.getArgs();
			//获取key
			String key = genKey(clazzName, methodName, args);

			o = handler.get(key);

			if(o==null){
				Object result = pjp.proceed();
				handler.set(key,new Model(17,"xiaoming"));
				o=result;
			}
		} catch (Throwable throwable) {
			throwable.printStackTrace();
		}
		return o;
	}

	private String genKey(String clazzName, String methodName, Object[] args) {
		StringBuilder sb = new StringBuilder(clazzName);
		sb.append("_");
		sb.append(methodName);
		if (args != null && args.length > 0) {
			for (Object obj : args) {
				sb.append("_");
				sb.append(stringToNull(obj));
			}
		}

		return sb.toString();
	}

	private String stringToNull(Object object) {
		return object == null ? "null" : object.toString();
	}

}
